//引入Vue
import Vue from "vue";
//引入路由
import VueRouter from "vue-router";
//引入vuex实例
import store from "@/store";

import { checkLogin, getAdminInfo } from "@/api/admin";

Vue.use(VueRouter)

//路由表 / 路由数组
const routes = [
  { path: "/", redirect: "/login" },
  {
    name: "login", path: "/login", component: () => import("@/views/LoginView.vue"),

  },

  {

    name: "main", path: "/main", component: () => import("@/views/MainView.vue"),
    children: [
      { name: "companyCheck", path: "companyCheck", component: () => import("@/views/CompanyCheckView.vue") },
      { name: "vipRule", path: "vipRule", component: () => import("@/views/VipRuleView.vue") },
      { name: "permission", path: "permission", component: () => import("@/views/PermissionAssignmentView.vue") },
      { name: "log", path: "log", component: () => import("@/views/LogManagementView.vue") },
      { name: "industry", path: "industry", component: () => import("@/views/IndustryView.vue") },
      { path: 'manageAdmin', name: 'manageAdmin', component: () => import("@/views/ManageAdmin.vue") },
      { path: 'manageUser', name: 'manageUser', component: () => import("@/views/ManageUser.vue") },
      { path: 'manageEnterprise', name: 'manageEnterprise', component: () => import("@/views/ManageEnterprise.vue") },
      { path: 'manageHr', name: 'manageHr', component: () => import("@/views/ManageHR.vue") },
      { path: 'managePosition', name: 'managePosition', component: () => import("@/views/ManagePosition.vue") },
      { path: 'reviewJobPosting', name: 'reviewJobPosting', component: () => import("@/views/ReviewJobPosting.vue") },
      { path: 'manageMenu', name: 'manageMenu', component: () => import("@/views/ManageMenu.vue") },
      { path: 'data', name: 'data', component: () => import("@/views/DataView.vue") },
      { path: 'dict', name: 'dict', component: () => import("@/views/DictView.vue") },
      { path: 'dictData', name: 'dictData', component: () => import("@/views/DictDataView.vue") },

      {
        name: "service", path: "service", component: () => import("@/views/ManService.vue"),
        children: [
          { name: "chat", path: 'chat/:id', component: () => import("@/views/ManChat.vue") },]
      },


    ]
  },
]

//创建路由实例
const router = new VueRouter({
  routes
})

//路由全局前置守卫
router.beforeEach(async (to, from, next) => {
  //放行白名单
  let whiteList = ["/login", "/"];


  /* 
  to.path：如果数组里面有，返回对应的索引；如果没有，返回-1
  */
  //判断是否是白名单

  if (whiteList.indexOf(to.path) != -1) {
    next();
    return;
  }

  try {

    //检查Vuex是否已有adminId
    if (!store.state.adminId) {
      const getInfoRes = await getAdminInfo();
      if (getInfoRes.code === 200) {
        // 等待Vuex更新完成
        await store.dispatch("getAdminInfo", getInfoRes.data);
      } else {
        alert("获取管理员信息失败");
        next("/login");
        return;
      }
    }
    next();
  } catch (error) {
    alert("网络异常，请重新登录");
    next("/login");
  }
})

//暴露
export default router;
